package com.honey.standard.writer.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.honey.compilation.java.JavaKeyWord;
import com.honey.core.compiler.CompilationType;
import com.honey.core.types.FullyQualifiedJavaType;

public class IoUtility {
	
 	private static SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
	
 	/**
 	 * 根据对象包找到对应的文件.
 	 * @param type 编译的包
 	 * @param fileType 文件类型
 	 * @return
 	 */
 	public final static File referenceFile(FullyQualifiedJavaType type , CompilationType fileType ){
		File answer = null;
		if( type != null){
			StringBuilder referencePath = new StringBuilder()
			.append(type.getLongName().replace('.', '/'))
			.append(JavaKeyWord.OPERATION_DOT)
			.append(fileType);
			answer = new File(referencePath.toString());
		}
		
		return answer;
	}
 	
	/**
	 * 在文件夹下获取指定文件,如果文件存在,寻找备份文件
	 * @param directory
	 * @param fileName
	 * @return
	 */
	public static final File uniqueFile(File directory, String fileName) {
		
		File answer = null;
		int index = fileName.lastIndexOf('.');
		String suffix = "";
		if (index > 0) {
			suffix = fileName.substring(index, fileName.length());
			fileName = fileName.substring(0, index);
		}
		StringBuilder sb = new StringBuilder();
		File testFile = null;
		String date = sf.format(new Date());
		
		for (int i = 1; i < 1000; i++) {
			sb.setLength(0);
			sb.append(fileName)
			.append('.')
			.append(date)
			.append('.')
			.append(i)
			.append(suffix);
			testFile = new File(directory, sb.toString());
			if (!testFile.exists()) {
				answer = testFile;
				break;
			}
			testFile = null;
		}
		return answer;
	}
	
	/**
	 * 使用Nio复制文件
	 * @param source
	 * @param dest
	 */
	public static final void copyFile( File source, File dest ) {
		FileChannel srcChannel = null;
		FileChannel dstChannel =  null;
		try {
			srcChannel = new FileInputStream( source ).getChannel();
			dstChannel = new FileOutputStream( dest ).getChannel();
			dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if (srcChannel != null)srcChannel.close();
				if (dstChannel != null)dstChannel.close();
			} catch (IOException e) {
			}
		}
	}
	
}
